同步更新於個人部落格
Serilog進階範例
選擇ASP.NET Core Web API專案範本,並執行下一步
命名你的專案名稱,並選擇專案要存放的位置。
直接進行下一步
using Serilog;
//第一階段初始化
// var builder = WebApplication.CreateBuilder(args);未使用二階段參數化,builder會跑到try外面
Log.Logger = new LoggerConfiguration()
//.ReadFrom.Configuration(builder.Configuration)
.CreateBootstrapLogger();
try {
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
//第二階段初始化可以取得appsetting的內容,如不使用第二階段初始化,
//會需要將 var builder宣告式會移出try(如上方註解處),就會有風險未捕獲builder的錯誤
builder.Host.UseSerilog(
(hostingContext, services, loggerConfiguration) => {
//使用appsetting
loggerConfiguration.ReadFrom.Configuration(builder.Configuration);
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment()) {
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
//紀錄每個Request的資料,須注意要放在讀取靜態檔案(app.UseStaticFiles())後面,因為靜態檔案的狀態通常不需要紀錄資訊
app.UseSerilogRequestLogging();
//以下省略
設定Serilog,包含
{
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft.AspNetCore": "Warning"
}
},
"WriteTo": [
{ "Name": "Console" },
{
"Name": "File",
"Args": {
"path": "./logs/log-.txt",
"rollingInterval": "Day"
}
},
{
"Name": "SQLite",
"Args": {
"sqliteDbPath": "../../../logs/log.sqlite",
"tableName": "Logs",
"maxDatabaseSize": 1
}
}
]
},
"AllowedHosts": "*"
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get() {
//新增一個類型
var StudentObject = new Student() { Id = 4, Name = "Bill", Age = 20 };
//新增一個匿名類型
var position = new { Latitude = 25, Longitude = 134 };
//寫log等級為error的log,當需要紀錄物件時需要透過{@該物件}來表示
_logger.LogError("Error Value: {@StudentObject}", StudentObject);
_logger.LogError("Error Value: {@position}", position);
return Enumerable.Range(1, 5).Select(index => new WeatherForecast {
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
public class Student {
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
F5執行後,依照下列步驟操作,並確認結果
執行後查看Log檔
點擊txt檔案後會看到我們所寫的Log檔案,會發現